import os
import hashlib
import json
import random
from typing import List
import requests
import time


def random_wait(num1, num2):

    wait_time = random.uniform(num1, num2)  # 生成一个介于1到5秒之间的随机浮点数
    print(f"Waited for {wait_time:.2f} seconds")

    time.sleep(wait_time)  # 等待指定的秒数


class RequestHanlder():

    def __init__(self):
        self.appkey = "1bN0kRdX8DVPGGvD5UdP"
        self.appSecret = "LzHQEv5nH8umSviagRdhK3lAJrYSMJpqe8QDuO8o"
        self.openid = "kjvb46f04fZ4uHQAbBBM"
        self.api = "https://gateway.rjmart.cn/open/shop"
        self.pre_api = "https://gateway.test.rj-info.com/open/shop"
        module_path = os.path.abspath(__file__)
        self.module_dir = os.path.dirname(module_path)
        if not os.path.exists(f"{self.module_dir}/cx/get_json"):
            os.makedirs(f"{self.module_dir}/cx/get_json")

        # 通过openid获取Access_Token
    def openid_Access_Token(self):
        """通过openid获取Access_Token"""
        url = "https://www.rjmart.cn/auth/openid/login"
        md5 = hashlib.md5()
        md5.update(self.appSecret.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        data = {"openid": self.openid, "sign": sign}
        response = requests.post(url=url, data=data)
        results = json.loads(response.content.decode("utf-8"))
        t = time.time()
        results.update({"time": t})
        with open(f"{self.module_dir}/cx/Access_Token_cx.json", mode="w") as f:
            f.write(json.dumps(results))
        return results

    def __no_data(self, url, name, data="/{/}"):
        """api基础模板"""
        time_now = time.time()
        with open(f"{self.module_dir}/cx/Access_Token_cx.json") as j:
            ac_json = json.load(j)
        Access_Token = ac_json["access_token"]
        time_acc = ac_json["time"]
        if time_now - time_acc > 600:
            Access_Token = self.openid_Access_Token()["access_token"]
        header = {
            "Authorization": f"Bearer {Access_Token}",
            "Content-Type": "application/json;charset=utf-8",
        }
        json_post_data = self.appSecret + data
        md5 = hashlib.md5()
        md5.update(json_post_data.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        s_url = f"{self.api}{url}?appkey={self.appkey}&sign={sign}"
        response = requests.post(
            url=s_url,
            **({
                "data": data.encode("utf-8")
            } if data else {}),
            headers=header,
            timeout=10,
        )
        results = response.content.decode("utf-8")
        with open(f"{self.module_dir}/cx/get_json/{name}.json",
                  mode="w",
                  encoding="utf-8") as f:
            f.write(results)
        return response

        # 查询入驻单位
    def settledOgrList(self):
        """查询入驻单位"""
        url = "/openapi/product/settledOgrList"
        name = "settledOgrList"
        return self.__no_data(url, name)

    def batchSaveOrUpdateProductV2(self, json_data):
        """批量新增、更新(新)"""
        url = "/openapi/product/saveProduct"
        name = "saveProduct"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)

    def saveOrUpdateProduct(self, json_data):
        """单个新增、更新"""
        url = "/openapi/product/saveOrUpdateProduct"
        name = "saveOrUpdateProduct"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)

    def updateProductInfoByCode(self, json_data):
        """批量更新（可部分更新）"""
        url = "/openapi/product/updateProductInfoByCode"
        name = "updateProductInfoByCode"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)

    def ProductsDetail(self, ProductIds: List[int]):
        """查询多个商品内容(id)
        单次支持查询50个
        """
        url = "/openapi/product/queryByProductIds"
        name = "ProductsDetail" + str(time.time())
        data = json.dumps(ProductIds)
        return self.__no_data(url, name, data=data)

    def ProductList(self, data_json):
        """
        批量查询商品（"status" : 3,      2:草稿，3:上架，4下架，5强制下架，12待审核，15已驳回
            *"brandIds" : [2],         品牌列表
            *"categoryId" : 1671,      分类id
            *"productNum" : "202200",  商品货号
            *"productName" : "测试商品"） 商品名
        """
        url = "/openapi/product/queryProductList"
        name = ("ProductList" + "&".join(list(map(str, data_json["brandIds"])))
                if data_json.get("brandIds", None) else "")
        data = json.dumps(data_json)
        return self.__no_data(url, name, data=data)

    def OffShelves(self, ProductIds):
        """批量下架"""
        url = "/openapi/product/offShelves"
        name = "OffShelves"
        data = json.dumps(ProductIds)
        return self.__no_data(url, name, data=data)